package com.student.Activitys.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.student.Activitys.R;
import com.student.Activitys.activity.base.BaseActivity;
import com.student.Activitys.adapter.EvaluateAdapter;
import com.student.Activitys.adapter.EvaluateResultAdapter;
import com.student.Activitys.bean.InfoReturnBean;
import com.student.Activitys.bean.ScheduleTestingBean;
import com.student.Activitys.bean.ScheduleWeekBean;
import com.student.Activitys.bean.pack.ScheduleTestingJsonPack;
import com.odd.Activitys.http.manager.HomeManager;
import com.student.Activitys.utils.Constant;
import com.student.Activitys.utils.ToastUtils;
import com.student.Activitys.view.recyleview.FullyLinearLayoutManager;
import com.willy.ratingbar.ScaleRatingBar;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 项目名称：智慧校园学生端
 * 类描述：阶段性评价 （期中、期末）
 * 创建人：张飞祥
 * 创建时间：2017/10/16 8:59
 * 修改人：张飞祥
 * 修改时间：2017/10/16 8:59
 * 修改备注：
 */
public class StageEvaluateActivity extends BaseActivity {
    @Bind(R.id.iv_return)
    ImageView ivReturn;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tv_stage_evaluate_teacher)
    TextView tvStageEvaluateTeacher;
    @Bind(R.id.tv_stage_evaluate_course)
    TextView tvStageEvaluateCourse;
    @Bind(R.id.rv_stage_evaluate_list)
    RecyclerView rvStageEvaluateList;
    @Bind(R.id.et_stage_evaluate_leave)
    EditText etStageEvaluateLeave;
    @Bind(R.id.btn_stage_evaluate_cr_submit)
    Button btnStageEvaluateCrSubmit;
    @Bind(R.id.layout_stage_evaluate_course)
    RelativeLayout layoutStageEvaluateCourse;
    @Bind(R.id.layout_bottom)
    AutoLinearLayout layoutBottom;

    //初始化网络请求
    public HomeManager mApiManager;
    //评价所需 星星 适配器
    private EvaluateAdapter adapter;
    //弹窗 dialog
    public MaterialDialog MsgDialog;
    //获取当前星星实体集合
    List<ScheduleTestingBean> list = null;
    //RecyclerView管理器
    LinearLayoutManager layoutManager = null;
    //传递过来的实体
    private ScheduleWeekBean weekBean;
    //评价类型
    private String pjStyle = "";

    @Override
    protected void initUI() {
        setContentView(R.layout.act_stage_evaluate);
        //网络请求 常驻方法
        mApiManager = mApiManager.getHomeApiManager(StageEvaluateActivity.this, StageEvaluateActivity.this.getTaskId());
    }

    @Override
    protected void initData() {
        // 获取传递过来的封了数据的Bundle
        Bundle bundle = this.getIntent().getExtras();
        // 获取 实体类
        weekBean = bundle.getParcelable(Constant.SCHEDULE_WEEK_BEAN);
        // 获取 评价类型
        pjStyle = bundle.getString(Constant.PJSTYLE);

        //显示返回按钮
        ivReturn.setVisibility(View.VISIBLE);
        //初始化请求
        initHttp();
    }

    @Override
    protected void getNotData() {

    }

    /**
     * 数据初始化
     */
    private void initHttp() {
        //课程
        tvStageEvaluateCourse.setText(weekBean.getKCM());
        //老师
        tvStageEvaluateTeacher.setText(weekBean.getTeacherName());
        //显示 加载dialog
        initShowTimeDialog("正在加载本页面数据，请稍后...",StageEvaluateActivity.this);
        /**
         * 标题 判断
         */
        if (weekBean.getSFPJ().equals("0")) {       //未评价
            if (pjStyle.equals(Constant.QZPJ))
                tvTitle.setText("期中评价");        //期中评价
            else if (pjStyle.equals(Constant.QMPJ))
                tvTitle.setText("期末评价");        //期末评价

            //开始网络请求 （未提交，刷新当前页面）
            mApiManager.stageSeeLoad(Constant.HTTP_HOME_STAGE_SEE_LOAD_ACTION);
            //显示layout
            layoutBottom.setVisibility(View.VISIBLE);
            //editText可编辑
            etStageEvaluateLeave.setFocusable(true);
        } else {                                     //已评价
            tvTitle.setText("评价详情");
            //开始网络请求（评价详情）
            mApiManager.stageSeeDetails(Constant.HTTP_EVALUATE_TESTING_ACTION, pjStyle, weekBean.getXNXQ(), xh, weekBean.getJSH(), weekBean.getKCH());
            //隐藏layout
            layoutBottom.setVisibility(View.GONE);
            //editText不可编辑
            etStageEvaluateLeave.setFocusable(false);
        }

    }

    /**
     * 阶段性评价 （当前页面刷新） 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_HOME_STAGE_LOAD_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initStageSeeLoadOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 阶段性评价 （当前页面刷新） 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_HOME_STAGE_LOAD, mode = ThreadMode.MAIN)
    public void stageSeeLoad(List<ScheduleTestingBean> list) {
        //装填星星集合
        this.list = list;
        //状态评价列表
        adapter = new EvaluateAdapter(StageEvaluateActivity.this, list);
        //管理器
        layoutManager = new LinearLayoutManager(StageEvaluateActivity.this, LinearLayoutManager.VERTICAL, false);
        //装填评价星星列表数据
        rvStageEvaluateList.setLayoutManager(layoutManager);
        rvStageEvaluateList.setAdapter(adapter);
    }

    /**
     * 阶段性评价 数据  评价提交 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_STAGE_SUBMIT_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initSubmitOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 阶段性评价 数据  评价提交 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_STAGE_SUBMIT_STAGE, mode = ThreadMode.MAIN)
    public void initSubmitList(InfoReturnBean bean) {
        if (bean.getState().equals("1")) {
            MsgDialog = new MaterialDialog.Builder(StageEvaluateActivity.this)
                    .title("成功")
                    .content(bean.getMsg())
                    .positiveText("确认")
                    .positiveColor(Color.GREEN)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            //刷新日课表
                            EventBus.getDefault().post("refresh", Constant.STAGE_SEE_REFRESH);
                            finish();
                        }
                    }).show();
        } else {
            MsgDialog = new MaterialDialog.Builder(StageEvaluateActivity.this)
                    .title("失败")
                    .content(bean.getMsg())
                    .negativeText("取消")
                    .positiveText("重试")
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            //刷新日课表
                            EventBus.getDefault().post("refresh", Constant.STAGE_SEE_REFRESH);
                            finish();
                        }
                    })
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            //重发
                            initSubmit();
                            dialog.dismiss();
                        }
                    }).show();
        }
        // 设置点击屏幕Dialog不消失
        MsgDialog.setCanceledOnTouchOutside(false);
        //取消Back键监听
        MsgDialog.setCancelable(false);
    }

    /**
     * 阶段性评价 数据 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_STAGE_SEE_DETAILS_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initTestingOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }
    /**
     * 阶段性评价 数据 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_STAGE_SEE_DETAILS_STAGE, mode = ThreadMode.MAIN)
    public void homeDynamic(final ScheduleTestingJsonPack pack) {
        //状态评价列表
        EvaluateResultAdapter adapter = new EvaluateResultAdapter(StageEvaluateActivity.this, pack.getPJFS());
        //塞入列表数据
        rvStageEvaluateList.setLayoutManager(new FullyLinearLayoutManager(StageEvaluateActivity.this, FullyLinearLayoutManager.VERTICAL, false));
        rvStageEvaluateList.setAdapter(adapter);
        //评价理由
        etStageEvaluateLeave.setText(pack.getPJLY());
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_return, R.id.btn_stage_evaluate_cr_submit})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:                        //退出
                finish();
                break;
            case R.id.btn_stage_evaluate_cr_submit:     //提交按钮
                initSubmit();
                break;
        }
    }

    /**
     * 数据提交
     */
    private void initSubmit() {
        String pjly = etStageEvaluateLeave.getText().toString();
        if (!pjly.equals("") && weekBean != null) {
            //显示 加载dialog
            initShowTimeDialog("正在提交您给出的评价，请稍后...",StageEvaluateActivity.this);
            //开始网络请求
            mApiManager.stageEvaluate(Constant.HTTP_EVALUATE_ACTION, pjStyle, weekBean.getXNXQ(), xh, weekBean.getJSH()
                    , weekBean.getKCH(), pjly, initIdArray(), initStarArray());
        } else {
            ToastUtils.showShort(StageEvaluateActivity.this, "评价内容不能为空");
        }
    }


    /**
     * 获取id数值集合
     */
    public String initIdArray() {
        String id = "";
        for (int i = 0; i < list.size(); i++) {
            if ((i + 1) == list.size())
                id += list.get(i).getId() + "";
            else
                id += list.get(i).getId() + ",";
        }
        return id;
    }

    /**
     * 获取星星数值集合
     */
    public String initStarArray() {
        String str = "";
        for (int i = 0; i < list.size(); i++) {
            View rvView = layoutManager.findViewByPosition(i);    //2为recyclerView中item位置，
            //获取父类视图
            AutoRelativeLayout layout = (AutoRelativeLayout) rvView;
            //获取子控件
            ScaleRatingBar score = (ScaleRatingBar) layout.findViewById(R.id.item_evaluate_score);
            float currentRating = score.getRating();
            if ((i + 1) == list.size())
                str += ((int) currentRating) + "";
            else
                str += ((int) currentRating) + ",";
        }
        return str;
    }
}
